<?php
/**
 * Created by PhpStorm.
 * User: UEWARE
 * Date: 2019-7-19
 * Time: 09:17:20
 */

namespace App\Http\Controllers\App;

use App\Factory\Sms;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class SmsController extends AppController
{
    /**
     * @param Request $request
     *
     * @param Sms     $Sms
     *
     * @return array
     * @throws \Exception
     */
    public function index(Request $request, Sms $Sms)
    {
        $mobile = $request->input('mobile');

        if (empty($mobile)) {
            return error(10001, '请填写手机号！');
        }

        // 生成4位随机数，左侧补0
        $code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);

        $expireTime = config('third_party.sms.captcha_expire_time');
        $template   = config('third_party.sms.template.captcha');
        $smsData    = [
            'code'   => $code,
            'expire' => $expireTime
        ];

        $Sms->send($mobile, $template, $smsData);

        $key       = 'verificationCode_' . str_random(15);
        $expiredAt = Carbon::now()->addMinutes($expireTime);

        // 缓存验证码 30分钟过期。
        Cache::put($key, ['mobile' => $mobile, 'code' => $code], $expiredAt);

        return success([
            'data' => [
                'key'        => $key,
                'expired_at' => $expiredAt->toDateTimeString()
            ]
        ]);
    }
}